<template>
  <div>
    <el-tree-select v-model="selectValue" :multiple="multiple" :data="shopTypesTreeList" check-strictly size="large"
      :render-after-expand="false" style="min-width: 240px;" placeholder="请选择商户类型" @change="changeValue" />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { ShopTypeAddAndEdit } from '@/api/index'
import Select from '@/components/admin/Select.vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  shopId: {
    type: String,
    default: '',
  },
  multiple: {
    type: Boolean,
    default: false
  }
})

const selectValue = ref('')

const changeValue = () => {
  let value = ''

  // let isArrary = Array.isArray(selectValue.value)


  if (props.multiple) {
    value = selectValue.value.join('|')
  } else {
    value = selectValue.value
  }

  emit('update:modelValue', value)
}

watch(() => props.modelValue, (newVal) => {
  if (props.multiple) {
    if (!newVal) return ''
    selectValue.value = newVal.toString().split('|').map(item => +item)
  } else {
    selectValue.value = newVal
  }
},
  {
    immediate: true
  }
)

const emit = defineEmits(['update:modelValue', 'change'])

// 方法 1: 使用递归和 Children.forEach
function flattenArray(arr) {
  return arr.reduce((acc, item) => {
    const { children, ...rest } = item;
    acc.push(rest);
    if (children && children.length > 0) {
      return acc.concat(flattenArray(children));
    }
    return acc;
  }, []);
}

// 商户分类详情
const shopTypesList = ref([])

const shopTypesTreeList = computed(() => {
  let res = shopTypesList.value.map((item) => {
    return {
      label: item.type_name,
      value: item.id,
      children: item.children.map((cItem) => {
        return {
          label: cItem.type_name,
          value: cItem.id,
        }
      }),
    }
  })

  // return flattenArray(res)
  return res
})

// 获取店铺分类
const getShopTypesRequest = async () => {
  try {
    const res = await ShopTypeAddAndEdit({
      method: 'list',
	  shopId:props.shopId
    })

    shopTypesList.value = res.data
  } catch (err) {
    console.log('getShopTypesRequest', err)
  }
}



getShopTypesRequest()
</script>

<style lang="scss" scoped></style>
